package com.konsung.ksdc.manager.machine;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.reflect.TypeToken;
import com.konsung.ksdc.R;
import com.konsung.ksdc.bean.netbean.MachineNetBean;
import com.konsung.ksdc.common.network.RequestCallback;
import com.konsung.ksdc.common.network.RequestUtils;
import com.konsung.ksdc.common.network.ResponseBean;
import com.konsung.ksdc.common.utils.Constants;
import com.konsung.ksdc.common.utils.DensityUtils;
import com.konsung.ksdc.common.utils.ToastUtils;
import com.konsung.ksdc.config.MyApplication;
import com.konsung.ksdc.config.NetConfig;
import com.konsung.ksdc.manager.appmain.BaseActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * 关联一体机界面
 * Created by Administrator on 2016/3/14 0014.
 */
public class MyMachineActivity extends BaseActivity implements View.OnClickListener {

    public static final int MSG_UPDATE = 10010; // 更新数据
    public static final int MGS_SHOW = 10000; // 显示进度条
    @Bind(R.id.ll_empty_message_container)
    LinearLayout llEmptyContainer;
    @Bind(R.id.btn_associate_machine)
    Button btnAssociateMachine;
    @Bind(R.id.rl_title_container)
    RelativeLayout rlTitleContainer;
    @Bind(R.id.tab_tv_title)
    TextView tvTitle;
    @Bind(R.id.rl_back)
    RelativeLayout rlBack;
    @Bind(R.id.ll_point_container)
    LinearLayout llPointContainer;

    public static final String CURRENT_MACHINE_NETBEAN = "machinenetbean";

    private final static int SCANNIN_GREQUEST_CODE = 1;
    @Bind(R.id.tv_save)
    TextView tvSave;
    @Bind(R.id.iv_counsel)
    ImageView ivCounsel;
    @Bind(R.id.vp_mac)
    ViewPager vpMac;
    @Bind(R.id.ll_cancel_relate)
    LinearLayout llCancelRelate;
    @Bind(R.id.ll_add_relate)
    LinearLayout llAddRelate;
    private MyMachineAdapter mMachineAdapter = new MyMachineAdapter();
    private List<MachineNetBean> machineList = new ArrayList<>();
    private List<View> mDots; // 底部小圆点的集合
    private ProgressDialog progressDialog;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            //定义一个Handler，用于处理下载线程与UI间通讯
            if (!Thread.currentThread().isInterrupted()) {
                switch (msg.what) {
                    case MGS_SHOW:
                        progressDialog.show(); // 显示进度对话框
                        break;
                    case MSG_UPDATE:
                        vpMac.setAdapter(new MacDetailAdapter(machineList));
                        hideDialog(); // 隐藏进度对话框，不可使用dismiss()、cancel()
                        // 否则再次调用show()时，显示的对话框小圆圈不会动。
                        initDots();
                        try {
                            Thread.sleep(200);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        break;
                    default:
                        break;
                }
            }
            super.handleMessage(msg);
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_machine);
        ButterKnife.bind(this);
        initEvent();
        initData();
        initView();

        checkEmpty();
    }

    /**
     * 初始化底部点集
     */
    private void initDots() {
        mDots = new ArrayList<View>(); // 底部圆点集合的初始化
        llPointContainer.removeAllViews();
        if (null != machineList && machineList.size() > 0) {
            // 根据界面数量动态添加圆点
            for (int i = 0; i < machineList.size(); i++) {
                View view = new View(this);
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(DensityUtils
                        .dp2px(this, 8), DensityUtils.dp2px(this, 8));
                layoutParams.setMargins(DensityUtils.dp2px(this, 5), 0, 0, 0);
                view.setLayoutParams(layoutParams);
                view.setBackgroundResource(R.drawable.point_nor);
                mDots.add(view); // 将该view添加到圆点集合中
                llPointContainer.addView(view); // 将view添加到LinearLayout中
            }
            mDots.get(0).setBackgroundResource(R.drawable.point_sel);
        }
    }

    /**
     * 初始化一体机关联页面
     */
    private void initView() {
        vpMac.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int
                    positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (null != machineList && machineList.size() > 0) {
                    for (int i = 0; i < machineList.size(); i++) {
                        //将所有的圆点设置为未选中状态
                        mDots.get(i).setBackgroundResource(R.drawable.point_nor);
                    }
                    //将被选中的page对应的圆点设置为被选中状态
                    mDots.get(position).setBackgroundResource(R.drawable.point_sel);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    /**
     * 初始化一体机关联页面点击事件
     */
    private void initEvent() {
        progressDialog = new ProgressDialog(MyMachineActivity.this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage(getString(R.string.dialog_tip_loading));
        progressDialog.setCancelable(true);
        progressDialog.show();

        btnAssociateMachine.setOnClickListener(this);
        llAddRelate.setOnClickListener(this);
        llCancelRelate.setOnClickListener(this);
    }

    /**
     * 检查是否有数据，如果没有数据，显示空信息文本
     */
    private void checkEmpty() {
        if (machineList.size() <= 0) {
            llEmptyContainer.setVisibility(View.VISIBLE);
        } else {
            llEmptyContainer.setVisibility(View.GONE);
        }
    }

    /**
     * 初始化一体机关联页面数据
     */
    private void initData() {
        tvTitle.setText(R.string.title_activity_my_mac);

        rlBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        reloadData();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_associate_machine:
                clickAssociate();
                break;
            case R.id.ll_add_relate:
                clickAssociate();
                break;
            case R.id.ll_cancel_relate:
                int currentItem = vpMac.getCurrentItem();
                if (machineList.size() > 0) {
                    relieveMac(NetConfig.currentEmpid, machineList
                            .get(currentItem).getId());
                } else {
                    Toast.makeText(MyApplication.getContext(), R.string.machine_no_relate,
                            Toast.LENGTH_SHORT).show();
                }

                break;
            default:
                break;
        }
    }

    /**
     * 确认解除关联对话框
     * @param empId 账号empId
     * @param macId 一体机机器id
     */
    private void relieveMac(final String empId, final String macId) {
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setTitle(getString(R.string.x_btn_remove_relate));
        dialog.setMessage(getString(R.string.mac_is_unrelate));
        dialog.setPositiveButton(getString(R.string.btn_yes), new
                DialogInterface.OnClickListener() {
                    // 退出按钮
                    @Override
                    public void onClick(DialogInterface dialog, int i) {
                        doRelieveMac(empId, macId);
                    }
                });
        dialog.setNegativeButton(getString(R.string.btn_no), new
                DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int i) {
                        //不退出不用执行任何操作
                    }
                });
        dialog.show();
    }

    /**
     * 解除关联
     * @param empId 账号empId
     * @param macId 一体机机器id
     */
    private void doRelieveMac(String empId, String macId) {
        RequestUtils.derelateMac(empId, macId, new RequestCallback() {
            @Override
            public void onError(Call call, Exception e) {
                ToastUtils.toastContent(MyMachineActivity.this,
                        getString(R.string.chat_unconnect));
            }

            @Override
            public void onResponse(ResponseBean responseBean) {
                String resultCode = responseBean.getResultCode();
                if (resultCode.equals(Constants.REQUEST_OK)) {
                    // ### 解除关联成功 ###
                    Toast.makeText(MyMachineActivity.this,
                            responseBean.getEntity(String.class),
                            Toast.LENGTH_SHORT).show();
                    reloadData();
                } else {
                    Toast.makeText(MyMachineActivity.this,
                            responseBean.getEntity(String.class),
                            Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    /**
     * 开始二维码扫描关联一体机
     */
    private void clickAssociate() {
        Intent intent = new Intent();
        intent.setClass(MyMachineActivity.this, MipcaActivityCapture.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra(MipcaActivityCapture.SCAN_TYPE_CODE, MipcaActivityCapture
                .TYPE_RELATE_MACHINE);
        startActivityForResult(intent, SCANNIN_GREQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent
            data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case SCANNIN_GREQUEST_CODE:
                if (resultCode == RESULT_OK) {
                    Bundle bundle = data.getExtras();
                    // 显示扫描到的内容: 一体机的序列号
                    String serialNum = bundle.getString("result");
                    if (!TextUtils.isEmpty(serialNum)) {
                        mHandler.sendEmptyMessage(MGS_SHOW);
                        findMachineBySerialNum(serialNum);
                        llEmptyContainer.setVisibility(View.GONE);
                        mMachineAdapter.notifyDataSetChanged();
                    }
                }
                break;
            default:
                break;
        }
    }

    /**
     * 查询服务端是否录入了该序列号的一体机
     * @param serialNum 一体机序列号
     */
    private void findMachineBySerialNum(String serialNum) {

        if (!RequestUtils.checkNetwork(MyMachineActivity.this)) {
            hideDialog();
            return;
        }
        RequestUtils.findMachineBySearialNum(serialNum, new
                RequestCallback() {
                    @Override
                    public void onError(Call call, Exception e) {
                        ToastUtils.toastContent(MyMachineActivity.this,
                                getString(R.string.chat_unconnect));
                    }

                    @Override
                    public void onResponse(ResponseBean responseBean) {
                        if (responseBean.getResultCode().equals(Constants
                                .REQUEST_OK)) {
                            MachineNetBean machineNetBean = responseBean.getEntity(MachineNetBean
                                    .class);
                            relateMac(NetConfig.currentEmpid, machineNetBean.getId());
                        } else {
                            // 机器未录入
                            Toast.makeText(MyMachineActivity.this, getString(R.string
                                    .machine__typing), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    /**
     * 关联一体机
     * @param empId 账号empId
     * @param macId 一体机机器id
     */
    private void relateMac(String empId, String macId) {

        RequestUtils.relateMac(empId, macId, new RequestCallback() {
            @Override
            public void onError(Call call, Exception e) {
            }

            @Override
            public void onResponse(ResponseBean responseBean) {
                String resultCode = responseBean.getResultCode();
                if (resultCode.equals(Constants.REQUEST_OK)) {
                    // 关联成功,数据发生变化
                    Toast.makeText(MyMachineActivity.this, responseBean
                            .getEntity(String.class), Toast.LENGTH_SHORT)
                            .show();
                    reloadData();
                } else {
                    // 关联失败
                    mHandler.sendEmptyMessage(MSG_UPDATE);
                    Toast.makeText(MyMachineActivity.this, responseBean
                            .getEntity(String.class), Toast.LENGTH_SHORT)
                            .show();
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected String activityDesc() {
        return getString(R.string.page_my_machine);
    }

    /**
     * 重新加载数据
     */
    private void reloadData() {
        if (!RequestUtils.checkNetwork(MyMachineActivity.this)) {
            hideDialog();
            return;
        }
        RequestUtils.findRelatedMac(NetConfig.currentEmpid, new
                RequestCallback() {
                    @Override
                    public void onError(Call call, Exception e) {
                        ToastUtils.toastContent(MyMachineActivity.this,
                                getString(R.string.chat_unconnect));
                        mHandler.sendEmptyMessage(MSG_UPDATE);
                    }

                    @Override
                    public void onResponse(ResponseBean responseBean) {
                        String resultCode = responseBean.getResultCode();
                        if (resultCode.equals(Constants.REQUEST_OK)) {
                            machineList = responseBean.getList(new
                                    TypeToken<List<MachineNetBean>>() {
                                    }.getType());
                            mHandler.sendEmptyMessage(MSG_UPDATE);
                            checkEmpty();
                        }
                    }
                });
        mMachineAdapter.setData(machineList);
        mMachineAdapter.notifyDataSetChanged();
    }

    /**
     * 隐藏dialog
     */
    public void hideDialog() {
        if (progressDialog != null) {
            progressDialog.hide();
        }
    }

    @Override
    protected void onDestroy() {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
        super.onDestroy();
    }
}
